//
//  QSShareCustomView.m
//  HYDClient
//
//  Created by apple on 2017/11/8.
//  Copyright © 2017年 gdzhibo. All rights reserved.
//

#import "QSShareCustomView.h"

#import "QSShareCustomViewCell.h"

#import <UMSocialCore/UMSocialCore.h>

@interface QSShareCustomView()<UICollectionViewDelegateFlowLayout, UICollectionViewDataSource>
/** 类型数组 */
@property (nonatomic, strong) NSArray *itemTypes;

/** 白色的容器view */
@property (nonatomic, weak) UIView *whiteView;

/** 半透明黑色View */
@property (nonatomic, weak) UIView *blackBgView;
@end

static NSString *ShareCustomViewCellID = @"ShareCustomViewCellID";

@implementation QSShareCustomView
SingleImplementation(QSShareCustomView);

- (void)createShareViewWithItemTypes:(NSArray<NSNumber *> *)itemTypes
{
    // 判断是否支持该分享平台
    NSMutableArray *tempArr = [itemTypes mutableCopy];
    for (NSNumber *platformType in itemTypes) {
        if (platformType.integerValue != QSShareToQRCode) {
            BOOL isInstall = [[UMSocialManager defaultManager] isInstall:platformType.integerValue];
            BOOL isSupport = [[UMSocialManager defaultManager] isSupport:platformType.integerValue];
            if (!isInstall || !isSupport) {
                [tempArr removeObject:platformType];
            }
        }
    }
    
    self.itemTypes = [NSArray arrayWithArray:tempArr];
    // 设置界面
    [self setupUIWithItemTypes:tempArr];
}

/**
 *  设置界面
 */
- (void)setupUIWithItemTypes:(NSArray *)itemTypes
{
    UIWindow *qs_window = kWindow;
    
    // 半透明遮罩view
    UIView *blackBgView = [[UIView alloc] init];
    blackBgView.backgroundColor = [UIColor clearColor];
    UITapGestureRecognizer *tapTop = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideShareView:)];
    [blackBgView addGestureRecognizer:tapTop];
    [qs_window addSubview:blackBgView];
    self.blackBgView = blackBgView;
    [blackBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.mas_equalTo(qs_window).offset(0);
    }];
    
    // 白色view
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectZero];
    whiteView.backgroundColor = [UIColor whiteColor];
    self.whiteView = whiteView;
    [qs_window addSubview:whiteView];
    [whiteView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(qs_window).offset(0);
        make.height.mas_equalTo(kScreenWidth / kLineCount * (self.itemTypes.count / kLineCount + (self.itemTypes.count % kLineCount > 0 ? 1 : 0)) + 50);
        make.bottom.mas_equalTo(qs_window).offset(kScreenWidth / kLineCount * (self.itemTypes.count / kLineCount + (self.itemTypes.count % kLineCount > 0 ? 1 : 0)) + 50);
    }];
    
    // title
    UILabel *titleLab = [[UILabel alloc] init];
    titleLab.text = @"分享";
    titleLab.textColor = kBlack_color;
    titleLab.font = [UIFont systemFontOfSize:16.0];
    titleLab.textAlignment =NSTextAlignmentCenter;
    [whiteView addSubview:titleLab];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(whiteView).offset(20.0);
        make.left.right.mas_equalTo(whiteView).offset(0);
    }];
    
    // 取消按钮
    UIButton *cancelBtn = [[UIButton alloc] init];
    [cancelBtn setImage:[UIImage imageNamed:@"icon_close"] forState:UIControlStateNormal];
    [whiteView addSubview:cancelBtn];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(whiteView).offset(10);
        make.right.mas_equalTo(whiteView).offset(-10);
        make.width.height.mas_equalTo(20);
    }];
    UIButton *bigCancelBtn = [[UIButton alloc] init];
    bigCancelBtn.backgroundColor = [UIColor clearColor];
    [bigCancelBtn addTarget:self action:@selector(clickCancelBtn) forControlEvents:UIControlEventTouchUpInside];
    [whiteView addSubview:bigCancelBtn];
    [bigCancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.mas_equalTo(cancelBtn).offset(-5);
        make.right.bottom.mas_equalTo(cancelBtn).offset(5);
    }];
    
    // 按钮的collectionview
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    UICollectionView *btnCollectionV = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
    btnCollectionV.backgroundColor = [UIColor whiteColor];
    flowLayout.itemSize = CGSizeMake(kScreenWidth / kLineCount, kScreenWidth / kLineCount);
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    btnCollectionV.delegate = self;
    btnCollectionV.dataSource = self;
    [whiteView addSubview:btnCollectionV];
    [btnCollectionV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(titleLab.mas_bottom).offset(10);
        make.left.right.bottom.mas_equalTo(whiteView).offset(0);
    }];
    
    // 注册
    [btnCollectionV registerClass:[QSShareCustomViewCell class] forCellWithReuseIdentifier:ShareCustomViewCellID];
    
    // 动画
    [whiteView.superview layoutIfNeeded];
    [UIView animateWithDuration:0.5 animations:^{
        [whiteView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(0);
            blackBgView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
        }];
        [whiteView.superview layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
}

- (void)hideShareView:(UITapGestureRecognizer *)tap
{
    [self clickCancelBtn];
}

/**
 *  点击取消按钮
 */
- (void)clickCancelBtn
{
    [UIView animateWithDuration:0.5 animations:^{
        [self.whiteView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(kScreenWidth / kLineCount * (self.itemTypes.count / kLineCount + (self.itemTypes.count % kLineCount > 0 ? 1 : 0)) + 50);
        }];
        self.blackBgView.backgroundColor = [UIColor clearColor];
        [self.whiteView.superview layoutIfNeeded];
    } completion:^(BOOL finished) {
        self.whiteView.hidden = YES;
        [self.whiteView removeFromSuperview];
        [self.blackBgView removeFromSuperview];
    }];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.itemTypes.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    QSShareCustomViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ShareCustomViewCellID forIndexPath:indexPath];
    NSNumber *shareType = [self.itemTypes objectAtIndex:indexPath.item];
    cell.sharePlatformType = shareType.integerValue;
    return cell;
}

#pragma mark - UICollectionViewDelegateFlowLayout
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    
    NSNumber *shareType = [self.itemTypes objectAtIndex:indexPath.item];
    [self shareWebPageToPlatformType:shareType.integerValue];
}

- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType
{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    // 图片大于32K，进行压缩
    NSData *data = [[NSData alloc] init];
    if ([self.shareThumbImg isKindOfClass:[UIImage class]]) {
        data = UIImageJPEGRepresentation(self.shareThumbImg, 1);
    } else if ([self.shareThumbImg isKindOfClass:[NSString class]]) {
        data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.shareThumbImg]];
        self.shareThumbImg = data;
    } else if ([self.shareThumbImg isKindOfClass:[NSData class]]) {
        data = self.shareThumbImg;
    }
    if (data.length > 32000) {
        UIImage *image = [UIImage imageWithData:data];
        UIImage *compressImage = [self compressImage:image toMaxFileSize:32000];
        self.shareThumbImg = compressImage;
    }
    //创建网页内容对象
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:self.shareTitle descr:self.shareDescription thumImage:self.shareThumbImg];
    //设置网页地址
    shareObject.webpageUrl = self.shareWebPageUrl;
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:nil completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                
                // 退出分享的view
                [self clickCancelBtn];
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
    }];
}

/**
 *  压缩图片
 */
- (UIImage *)compressImage:(UIImage *)image toMaxFileSize:(NSInteger)maxFileSize
{
    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.1f;
    NSData *imageData = UIImageJPEGRepresentation(image, compression);
    while ([imageData length] > maxFileSize && compression > maxCompression) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(image, compression);
    }
    
    UIImage *compressedImage = [UIImage imageWithData:imageData];
    return compressedImage;
}
@end
